package com.gwz.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gwz.sys.domain.Role;
import com.gwz.sys.mapper.RoleMapper;
import com.gwz.sys.service.RoleService;
import com.gwz.sys.utils.DataGridView;
import com.gwz.sys.vo.RoleVo;

@Service
@Transactional
public class RoleServiceImpl implements RoleService{
	
	@Autowired
	private RoleMapper roleMapper;


	@Override
	public DataGridView queryAllRole(RoleVo roleVo) {
		Page<Object> page=PageHelper.startPage(roleVo.getPage(), roleVo.getLimit());
		List<Role> data = this.roleMapper.queryAllRole(roleVo);
		return new DataGridView(page.getTotal(), data);
	}


	@Override
	public void addRole(RoleVo roleVo) {
		this.roleMapper.insertSelective(roleVo);
	}

	@Override
	public void updateRole(RoleVo roleVo) {
		this.roleMapper.updateByPrimaryKeySelective(roleVo);
	}

	@Override
	public void deleteRole(RoleVo roleVo) {
		this.roleMapper.deleteByPrimaryKey(roleVo.getId());
	}


	@Override
	public void saveRolePermission(RoleVo roleVo) {
		Integer rid = roleVo.getId();
		Integer[] ids = roleVo.getIds();
		//删除角色和权限的老关系
		roleMapper.deleteRolePermissionByRoleId(rid);
		//保存角色和权限的新关系
		for (Integer pid : ids) {
			roleMapper.saveRolePermission(rid,pid);
		}
	}


	@Override
	public List<String> queryAllRoleByUserId(Integer userId) {
		List<Role> list = roleMapper.queryRoleByUserId(userId);
		List<String> roles = new ArrayList<>();
		for (Role role : list) {
			roles.add(role.getName());
		}
		return roles;
	}

}
